package com.tao.common.security.interceptor;

import cn.hutool.core.util.StrUtil;
import com.tao.common.creo.Utils.ThreadLocalUtil;
import com.tao.common.creo.constants.HttpConstants;
import com.tao.common.creo.constants.Constants;
import com.tao.common.security.service.TokenService;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * token 拦截器, 拦截校验token的合法性
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;
    @Value("${jwt.secret}")
    private String secret;



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        System.out.println("requestURI: " + requestURI);
        String token = getToken(request);
        if(token.isEmpty()) {
            return false;
        }
        // 解析token, 从token中获取userId
        Claims claims = tokenService.getClaims(token, secret);
        Long userId = tokenService.getUserId(claims);
        // 将userId存储到 TransmittableThreadLoca中
        ThreadLocalUtil.set(Constants.USER_ID, userId);
        Long aLong = ThreadLocalUtil.get(Constants.USER_ID, Long.class);
        tokenService.extendToken(userId);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }

    /**
     * 根据请求获取token
     * @param request 请求
     */
    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(HttpConstants.AUTHENTICATION);
        // 校验token 是否为空, 并且是否包含前缀 Bearer
        if(StrUtil.isNotBlank(token) && token.startsWith(HttpConstants.PREFIX)) {
            // 删除token的前缀
            token.replace(HttpConstants.PREFIX, "");
        }
        return token;
    }
}
